<?php
namespace common\models\group;

use common\models\Common;
use common\models\friend\FriendApply;
use common\models\Functions;
use common\models\im\Im;
use common\models\im\ImQrcode;
use common\models\Status;
use common\models\user\User;
use Yii;
use yii\base\Exception;
use yii\helpers\ArrayHelper;

/**
 * This is the model class for table "goods".
 *
 * @property int $id
 * @property string $name
 */
class Group extends Common
{


    public static function tableName()
    {
        return '{{%group}}'; // TODO: Change the autogenerated stub
    }

    public function getUser()
    {
        return $this->hasMany(GroupUser::className(), ['group_id' => 'id']);
    }

    public function getOwner()
    {
        return $this->hasOne(User::className(), ['id' => 'user_id']);
    }

    // 创建腾讯code
    public function createTxCode()
    {
        do {
            $txCode = Functions::generateCode(10).date('Ymd');
            $exist = static::getOneByWhere(['tx_code' => $txCode]);
        } while ($exist > 0);
        return $txCode;
    }

    // 创建code
    public function createCode()
    {
        do {
            $code = Functions::generateCode(10);
            $exist = static::getOneByWhere(['code' => $code]);
        } while ($exist > 0);
        return $code;
    }

    // 修改群头像
    public function _updateGroupPic($groupId = 0) {
        $groupInfo = static::getOneInfoById($groupId);

        $groupUserList = GroupUser::getObjectByWhere(['group_id' => $groupId], ['user_id',"user_face","user_nick_name"])->with([
            'user' => function ($q) {
                $q->select(['id', 'user_face']);
            },
        ])->asArray()->all();

        // 群未上传新头像时  一直更新头像
        if ($groupInfo['is_update_image'] == Status::COMMON_RADIO_NO) {
            $groupPicList = [];
            foreach ($groupUserList as $value) {
                $singleUser = ArrayHelper::getValue($value, 'user');
//                array_push($groupPicList, static::getAvatar($singleUser['user_face']));
                array_push($groupPicList, static::getAvatar($singleUser['user_face']));
            }
            $groupFace = (new ImQrcode())->groupPic($groupPicList);
            $updateGroupData['image'] = $groupFace;

            // 更新IM群信息
            $updateImGroupData['FaceUrl'] = static::getImages($groupFace);
            (new Im())->updateImGroup($groupInfo['tx_code'], $updateImGroupData);
        }

        $groupImInfo = (new Im())-> getGroupInfo($groupInfo['tx_code']);
        $updateGroupData['user_num'] = $groupImInfo['MemberNum'];
        $resUpdateGroup = Group::updateData($updateGroupData, ['id' => $groupId]);
//        if ($resUpdateGroup === false) {
//            throw new Exception('操作失败！');
//        }
    }


    /**
     * 自动创建群聊
     * @param array $owner 群主
     * @param array $groupWithUser  群员  二维数组
     * @return mixed
     * @throws Exception
     */
    public function createImGroup($owner = [], $groupWithUser = []) {
        if (empty($owner)) {
            throw new Exception('未知群主信息！');
        }

        // 建群
        $groupData['code'] = $this->createCode();
        $groupData['tx_code'] = $this->createTxCode();
        $groupData['name'] = '群聊'.$groupData['code'];
        $groupData['image'] = "";
        $groupData['user_id'] = $owner['id'];
        $groupData['user_tx_code'] = $owner['tx_code'];
        $groupData['user_code'] = $owner['user_code'];
        $groupData['qr_code'] = "";
        $groupData['user_num'] = 0;
        $groupData['notice'] = "暂未设置";
        $groupData['status'] = Status::COMMON_RADIO_YES;
        $groupData['is_shut_up'] = Status::COMMON_RADIO_NO;
        $groupData['create_time'] = date('Y-m-d H:i:s');
        $groupId = static::insertData($groupData);
        if ($groupId === false) {
            throw new Exception('群创建失败！');
        }
        // 头像
        $groupPicList = [];

        // 创建群主
        $groupUser['group_id'] = $groupId;
        $groupUser['group_tx_code'] = $groupData['tx_code'];
        $groupUser['group_code'] = $groupData['code'];
//        $groupUser['group_name'] = $groupData['name'];
//        $groupUser['group_image'] = $groupData['image'];
        $groupUser['user_id'] = $owner['id'];
        $groupUser['user_tx_code'] = $owner['tx_code'];
        $groupUser['user_face'] = $owner['user_face'];
        $groupUser['user_nick_name'] = $owner['nick_name'];
//        $groupUser['business_card'] = $owner['nick_name'];
        $groupUser['business_card'] = '';
        $groupUser['user_code'] = $owner['user_code'];
        $groupUser['user_phone'] = $owner['login_name'];
        $groupUser['user_type'] = Status::GROUP_USER_TYPE_HOME;
        $groupUser['is_shut_up'] = Status::COMMON_RADIO_NO;   //禁言
        $groupUser['is_not_disturbing'] = Status::COMMON_RADIO_NO;   //是否消息免打扰
        $groupUser['is_receive_red_packet'] = Status::COMMON_RADIO_YES;  // 是否可以抢红包
        $groupUser['create_time'] = date('Y-m-d H:i:s');
        $groupUser['enter_type'] = Status::GROUP_USER_JOIN_TYPE_INVITE; //1-申请进群  2-邀请进群
        $groupUser['invite_user_id'] = $owner['id'];
        $groupUser['invite_user_phone'] = $owner['login_name'];
        $groupUser['invite_user_tx_code'] = $owner['tx_code'];
        $groupUser['invite_user_code'] = $owner['user_code'];
        $groupUserRes = GroupUser::insertData($groupUser);
        if ($groupUserRes === false) {
            throw new Exception('群创建失败！');
        }
        array_push($groupPicList,static::getAvatar($owner['user_face']));


        // 腾讯群员list
        $memberList = [];
        $singleMember['Member_Account'] = (string) $owner['tx_code'];
        $singleMember['NameCard'] = $owner['nick_name'];
        $singleMember['enter_type'] = (string) Status::GROUP_USER_JOIN_TYPE_INVITE;
        $singleMember['invite_code'] = (string) $owner['tx_code'];
        array_push($memberList,$singleMember);

        // 群成员信息
        if ($groupWithUser) {
            foreach ($groupWithUser as $key => $friendUser) {

                $isFriend = ArrayHelper::getValue($friendUser,'isFriend',[]);
                // 是否是好友
                if (empty($isFriend)) {
                    continue;
                }

                // 申请信息 需要本人同意
                if ($friendUser['is_auto_enter_group'] == Status::COMMON_RADIO_NO) {
                    // 需要本人同意
                    $groupApplyData = [];
                    $groupApplyData['user_id'] = $friendUser['id'];
                    $groupApplyData['user_phone'] = $friendUser['login_name'];
                    $groupApplyData['user_code'] = $friendUser['user_code'];
                    $groupApplyData['user_nick_name'] = $friendUser['nick_name'];
                    $groupApplyData['user_face'] = $friendUser['user_face'];
                    $groupApplyData['user_tx_code'] = $friendUser['tx_code'];
                    $groupApplyData['enter_type'] = Status::GROUP_USER_JOIN_TYPE_INVITE; //1-申请进群  2-邀请进群
                    $groupApplyData['message'] = $owner['login_name']."创建群聊邀请进群";
                    $groupApplyData['status'] = Status::COMMON_CHECKING_WAITING;
                    $groupApplyData['group_id'] = $groupId;
                    $groupApplyData['group_code'] = $groupData['code'];
                    $groupApplyData['group_image'] = $groupData['image'];
                    $groupApplyData['group_name'] = $groupData['name'];
                    $groupApplyData['group_tx_code'] = $groupData['tx_code'];
                    $groupApplyData['create_time'] = date('Y-m-d H:i:s');
                    $groupApplyData['invite_user_id'] = $owner['id'];
                    $groupApplyData['invite_user_phone'] = $owner['login_name'];
                    $groupApplyData['invite_user_tx_code'] = $owner['tx_code'];
                    $groupApplyData['invite_user_code'] = $owner['user_code'];
                    $groupApplyData['be_invited_status'] = Status::COMMON_CHECKING_WAITING;
                    $groupApplyRes = GroupApply::insertData($groupApplyData);
                    if ($groupApplyRes === false) {
                        throw new Exception('群创建失败！');
                    }

                    //  发送个人邀请信息
                    FriendApply::notReadApplyNum($friendUser['id']);

                } else {
                    // 不需要本人同意 直接进群
                    $groupUser = [];
                    $groupUser['group_id'] = $groupId;
                    $groupUser['group_tx_code'] = $groupData['tx_code'];
                    $groupUser['group_code'] = $groupData['code'];
//                $groupUser['group_name'] = $groupData['name'];
//                $groupUser['group_image'] = $groupData['image'];
                    $groupUser['user_id'] = $friendUser['id'];
                    $groupUser['user_tx_code'] = $friendUser['tx_code'];
                    $groupUser['user_face'] = $friendUser['user_face'];
                    $groupUser['user_nick_name'] = $friendUser['nick_name'];
//                $groupUser['business_card'] = $friendUser['nick_name'];
                    $groupUser['business_card'] = '';
                    $groupUser['user_code'] = $friendUser['user_code'];
                    $groupUser['user_phone'] = $friendUser['login_name'];
                    $groupUser['user_type'] = Status::GROUP_USER_TYPE_NORMAL;
                    $groupUser['is_shut_up'] = Status::COMMON_RADIO_NO;   //禁言
                    $groupUser['is_not_disturbing'] = Status::COMMON_RADIO_NO;   //是否消息免打扰
                    $groupUser['is_receive_red_packet'] = Status::COMMON_RADIO_YES;  // 是否可以抢红包
                    $groupUser['create_time'] = date('Y-m-d H:i:s');
                    $applyData['enter_type'] = Status::GROUP_USER_JOIN_TYPE_INVITE; //1-申请进群  2-邀请进群
                    $groupUser['invite_user_id'] = $owner['id'];
                    $groupUser['invite_user_phone'] = $owner['login_name'];
                    $groupUser['invite_user_tx_code'] = $owner['tx_code'];
                    $groupUser['invite_user_code'] = $owner['user_code'];
                    $groupUserRes = GroupUser::insertData($groupUser);
                    if ($groupUserRes === false) {
                        throw new Exception('群创建失败！');
                    }
                    array_push($groupPicList,static::getAvatar($friendUser['user_face']));

                    $singleMember['Member_Account'] = (string) $friendUser['tx_code'];
                    $singleMember['NameCard'] = $friendUser['nick_name'];
                    $singleMember['enter_type'] = (string) Status::GROUP_USER_JOIN_TYPE_INVITE;
                    $singleMember['invite_code'] = (string) $owner['tx_code'];
                    array_push($memberList,$singleMember);
                }
            }
        }


        $imModel = new Im();
        // 上传群头像
        $imQrCodeModel = new ImQrcode();
        $groupFace = $imQrCodeModel->groupPic($groupPicList);
        $groupQrCode = $imQrCodeModel->groupQrCode($groupId, $groupData['tx_code']);

        $groupData['image'] = $updateGroupData['image'] = $groupFace;
        $groupData['qr_code'] = $updateGroupData['qr_code'] = $groupQrCode;
        $groupData['user_num'] = $updateGroupData['user_num'] = count($memberList);
        $resUpdateGroup = static::updateData($updateGroupData,['id' => $groupId]);
        if ($resUpdateGroup === false) {
            throw new Exception('操作失败！');
        }

        // 创建群
        $addImGroupRes = $imModel -> addImGroup($groupData, $owner, $memberList, $groupId, static::getImages($groupFace), static::getImages($groupQrCode));
        if (!$addImGroupRes) {
            throw new Exception('群创建失败！');
        }

        // 发送im消息
        $publicGroupMessage['message_type'] = Status::MESSAGE_TYPE_GROUP_PUBLIC;
        $publicGroupMessage['type'] = Status::MESSAGE_TYPE_GROUP_USER_CREATE_GROUP;
        $publicGroupMessage['oneTxCode'] = $owner['tx_code'];
        $publicGroupMessage['oneNickName'] = $owner['nick_name'];
        $publicGroupMessage['content'] = $owner['nick_name']."创建了群聊！";
        $imModel->sendGroupMessage($groupData['tx_code'], $publicGroupMessage);

        $groupData['id'] = $groupId;
        return $groupData;

    }

    /**
     * 解散群
     * @param int $userId
     * @param int $groupId
     * @param string $groupTxCode
     * @throws Exception
     */
    public function delGroup($userId = 0, $groupId = 0, $groupTxCode = '') {

        // 群成员信息  群申请信息全都删除 与 群信息
        $resGroupUserDel = GroupUser::deleteAll(['group_id' => $groupId]);
        if ($resGroupUserDel === false) {
            throw new Exception('群解散失败1！');
        }

        $resGroupApplyDel = GroupApply::deleteAll(['group_id' =>$groupId]);
        if ($resGroupApplyDel === false) {
            throw new Exception('群解散失败2！');
        }

        $resGroupDel = static::deleteAll(['id' => $groupId]);
        if ($resGroupDel === false) {
            throw new Exception('群解散失败3！');
        }


        // IM解散群
        $resImDel = (new Im())->delGroup($groupTxCode);
//        if (!$resImDel) {
//            throw new Exception('群解散失败4！');
//        }

//        // 发送未读通知
//        FriendApply::notReadApplyNum($userId, $groupId);

    }



}
